<template>
  <el-row>
    <el-tabs type="border-card">
      <el-tab-pane label="风险溯源">
        <div class="btn">
          <el-select v-model="selectedDataset" placeholder="选择数据集">
            <el-option
              v-for="dataset in datasets"
              :key="dataset.id"
              :label="dataset.name"
              :value="dataset.value"
            />
          </el-select>

          <!-- 只有当 selectedDataset 有值时，按钮才可用。 -->
          <el-button
            type="primary"
            :disabled="selectedDataset === ''"
            :loading="startFlag"
            style="width: 100px"
            @click="start"
            >开始</el-button
          >

          <!-- <el-button type="danger" :disabled="!startFlag" style="width: 100px"
          >暂停</el-button> -->
        </div>
        <div class="form" v-if="completedFlag">
          <el-table :data="AllNodes" border style="width: 100%">
            <el-table-column
              align="center"
              prop="nodeName"
              label="节点名称"
              sortable
            ></el-table-column>
                        <el-table-column
                          align="center"
                          prop="infectionIntensity"
                          label="被感染强度"
                          sortable
                        ></el-table-column>
                        <el-table-column
                          align="center"
                          prop="riskProbability"
                          label="风险源概率"
                          sortable
                        ></el-table-column>
                        <el-table-column
                          align="center"
                          prop="riskImportance"
                          label="风险源重要性"
                          sortable
                        ></el-table-column>
          </el-table>
          <div class="btn1">
            <el-button
              type="primary"
              :disabled="mapFlag === 'infection'"
              style="width: 140px"
              @click="infectionMap"
              >被感染强度</el-button
            >
            <el-button
              type="primary"
              :disabled="mapFlag === 'riskProbability'"
              style="width: 140px"
              @click="riskProbabilityMap"
              >风险源概率</el-button
            ><el-button
              type="primary"
              :disabled="mapFlag === 'riskImportance'"
              style="width: 140px"
              @click="riskImportanceMap"
              >风险源重要性</el-button
            >
          </div>
        </div>
        <el-card style="margin-top: 10px"
          ><div ref="networkContainer" style="width: 100%; height: 600px"></div
        ></el-card>
      </el-tab-pane>
    </el-tabs>
  </el-row>
</template>

<script>
import http from '../utils/request'

import { DataSet, Network } from 'vis'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      selectedDataset: '',
      datasets: [
        {
          id: 1,
          name: '股票',
          value: 'dataGP',
        },
        {
          id: 2,
          name: '期货',
          value: 'dataQH',
        },
        {
          id: 3,
          name: '债券',
          value: 'dataZQ',
        },
      ],
      startFlag: false,
      completedFlag: false,
      searchQuery: '',
      nodes: new DataSet([]),
      edges: new DataSet([]),
      network: null,
      nextId: 2,
      mapFlag: 'infection',
      maxValue: 1,
      minValue: 0,
    }
  },
  computed: {
    ...mapGetters({
      // 从 store 中获取数据，并且数据会随着 store 中的数据变化而变化
      dataset: 'getDataset',
      AllNodes: 'getAllNodes',
      AllEdges: 'getAllEdges',
    }),
    filteredTableData() {
      if (!this.searchQuery) return this.tableData
      return this.tableData.filter((item) =>
        item.nodeName.includes(this.searchQuery)
      )
    },
  },
  methods: {
    infectionMap() {
      // 清空原有数据
      this.nodes.clear()
      this.edges.clear()
      // 筛选最大值和最小值
      this.AllNodes.forEach((item) => {
        if (item.infectionIntensity > this.maxValue) {
          this.maxValue = item.infectionIntensity
        }
        if (item.infectionIntensity < this.minValue) {
          this.minValue = item.infectionIntensity
        }
      })
      this.AllNodes.forEach((item) => {
        this.nodes.add({
          id: item.id,
          label: item.nodeName,
          color: this.getInterpolatedColor(item.infectionIntensity),
          font: { color: 'white' },
        })
      })

      this.AllEdges.forEach((item) => {
        this.edges.add({
          from: item.from,
          to: item.to,
        })
      })
      this.mapFlag = 'infection'
      this.initNetwork()
    },
    riskProbabilityMap() {
      this.nodes.clear()
      this.edges.clear()
      // 筛选最大值和最小值
      this.AllNodes.forEach((item) => {
        if (item.riskProbability > this.maxValue) {
          this.maxValue = item.riskProbability
        }
        if (item.riskProbability < this.minValue) {
          this.minValue = item.riskProbability
        }
      })
      this.AllNodes.forEach((item) => {
        this.nodes.add({
          id: item.id,
          label: item.nodeName,
          color: this.getInterpolatedColor(item.riskProbability),
          font: { color: 'white' },
        })
      })
      this.AllEdges.forEach((item) => {
        this.edges.add({
          from: item.from,
          to: item.to,
        })
      })
      this.mapFlag = 'riskProbability'
      this.initNetwork()
    },
    riskImportanceMap() {
      this.nodes.clear()
      this.edges.clear()
      // 筛选最大值和最小值
      this.AllNodes.forEach((item) => {
        if (item.riskImportance > this.maxValue) {
          this.maxValue = item.riskImportance
        }
        if (item.riskImportance < this.minValue) {
          this.minValue = item.riskImportance
        }
      })
      this.AllNodes.forEach((item) => {
        this.nodes.add({
          id: item.id,
          label: item.nodeName,
          color: this.getInterpolatedColor(item.riskImportance),
          font: { color: 'white' },
        })
      })
      this.AllEdges.forEach((item) => {
        this.edges.add({
          from: item.from,
          to: item.to,
        })
      })
      this.mapFlag = 'riskImportance'
      this.initNetwork()
    },
    start() {
      this.startFlag = true
      this.datasets.forEach((item) => {
        if (item.value === this.selectedDataset) {
          this.$store.commit('changeDataset', item.name)
        }
      })
      // request({
      //   url: `/tracetosource/findsource?query=Test_data`,
      //   // url: `/tracetosource/findsource?query=${this.selectedDataset}`,
      //   method: 'get',
      // })
          http.get(`/tracetosource/findsource?query=${this.selectedDataset}`).then((res) => {
        this.completedFlag = true
        this.startFlag = false
        let list = []
        console.log('res.data', res.data)
        for (let i = 0; i < res.data.length; i++) {
          list.push({
            id: res.data[i],
            nodeName: res.data[i],
          })
        }

        this.$store.commit('changeAllNodes', list) // 修改 store 中的数据，这里传入的是一个经过处理的list，是因为需要符合table展示的格式，先将他处理了，再存储到store中，这样在其他组件中也可以直接使用
        // this.$store.commit('changeAllEdges', res.data.AllEdges)
      })
      // let datamap = new Map();
      //   datamap.set("dataGP", 1);
      //   datamap.set("dataQH", 2);
      //   datamap.set("dataZQ", 3);
      http.get(`/tracetosource/set_global_dataset_value?query=${this.selectedDataset}`).then(res => {
        console.log('全局变量设置响应:', res.data)
      })
    },
    getInterpolatedColor(value) {
      const startColor = { r: 0, g: 0, b: 255 }
      const endColor = { r: 255, g: 0, b: 0 }
      const ratio = Math.max(
        0,
        Math.min((value - this.minValue) / (this.maxValue - this.minValue), 1)
      )
      const r = Math.round(startColor.r + (endColor.r - startColor.r) * ratio)
      const g = Math.round(startColor.g + (endColor.g - startColor.g) * ratio)
      const b = Math.round(startColor.b + (endColor.b - startColor.b) * ratio)
      return `#${[r, g, b]
        .map((x) => x.toString(16).padStart(2, '0'))
        .join('')}`
    },

    //包含了获取数据集数据，和
    fetchSourceData() {
      console.log('fetchSourceData')
      this.tableData = []
      //当下拉框被选择时，自动更新 selectedDataset 为对应选项的value。
      if (!this.selectedDataset) return
      http
        .get('api/nodes/findsource', {
          params: { dataset: this.selectedDataset },
        })
        .then((res) => {
          this.AllEdges = res.data.edges
          this.AllNodes.res.data.nodes
        })
        .catch((err) => console.error('数据获取失败:', err))
    },

    initNetwork() {
      const container = this.$refs.networkContainer
      this.network = new Network(
        container,
        { nodes: this.nodes, edges: this.edges },
        { physics: true }
      )
    },
  },
  mounted() {
    console.log('this.state', this.$store.getters.getDataset)
    console.log('this.state', this.$store.getters.getDataset)
    // this.getDatasets()// 组件加载时自动请求数据
  },
}
</script>

<style scoped>
.form {
  margin: 20px;
}
.btn {
  width: 50%;
  margin-left: 20px;
  display: flex;
  justify-content: space-around;
}
.btn1 {
  margin: 20px;
  display: flex;
  justify-content: center;
  /* color: rgb(255, 0, 0); */
}
</style>
